package com.ias.agdis_r.activity.more;

import android.app.ActionBar;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.provider.MediaStore;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.ias.agdis_r.R;
import com.ias.agdis_r.activity.BaseKeyActivity;
import com.ias.agdis_r.activity.MainActivity;
import com.ias.agdis_r.adapter.PhotoAdapter;
import com.ias.agdis_r.bean.auth.AuthEnum;
import com.ias.agdis_r.manager.DataBaseManager;
import com.ias.agdis_r.manager.DataManager;
import com.ias.agdis_r.manager.EffectManager;
import com.ias.agdis_r.manager.JavaBeanManager;
import com.ias.agdis_r.util.S;
import com.ias.agdis_r.util.UpdateFile;
import com.ias.agdis_r.util.sdcard.SDcard;
import com.ias.agdis_r.util.sdcard.WriteLog;

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.List;

/**
 * 图库-图片列表
 * @author zhangsc
 *
 */
public class PhotoAlbumActivity extends BaseKeyActivity {
	
	private GridView gridview_photo;
	private PhotoAdapter photoAdapter;
	private ActionBar actionBar;
	private LinearLayout layout_select,layout_delete,layout_camera,layout_upload;
	private ImageView img_select;
	private AlertDialog dialog;
	String photo_name = "";
	private boolean isLoad = false;
	public ProgressDialog pd;    //进度条对话框
	private UploadTask uploadTask = null;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_photo_album);
		actionBar = getActionBar();
		loadactionbar();
		gridview_photo = (GridView) findViewById(R.id.gridview_photo);  
		layout_select = (LinearLayout)findViewById(R.id.layout_select);
		layout_delete = (LinearLayout)findViewById(R.id.layout_delete);
		layout_camera = (LinearLayout)findViewById(R.id.layout_camera);
		layout_upload = (LinearLayout)findViewById(R.id.layout_upload);
		img_select = (ImageView)findViewById(R.id.img_select);
		photoAdapter = new PhotoAdapter(this);
		checkInfo();
		gridview_photo.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> parent, View view,
									int position, long id) {
				// TODO Auto-generated method stub
				//如果可选中状态
				if (photoAdapter.isCheckable()) {
					//选中图片
					photoAdapter.select(position, view);
				} else {
					if (!isLoad) {
						isLoad = true;
						//跳转到详情页面
						Intent intent = new Intent(PhotoAlbumActivity.this, PhotoDetailActivity.class);
						File file = photoAdapter.getItem(position);
						intent.putExtra("photo", file);
						startActivity(intent);
					}
				}
			}
		});
		
		
		layout_select.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO 反选
				boolean checkedable = !photoAdapter.isCheckable();
				if (checkedable) {
					img_select.setImageResource(R.drawable.toolbar_select_focus);
					layout_delete.setVisibility(View.VISIBLE);
					//如果具有照片上传的权限
					boolean photoUpload = JavaBeanManager.getInstance().adjust_pri(AuthEnum.AI_T_PHOTOUPLOAD.toString());
					if(photoUpload) {
						layout_upload.setVisibility(View.VISIBLE);
					}
					EffectManager.getInstance().ttsPlay(
							EffectManager.TTS_TYPE_TASK, getString(R.string.chooseStart), false);
				} else {
					img_select.setImageResource(R.drawable.toolbar_select);
					layout_delete.setVisibility(View.GONE);
					layout_upload.setVisibility(View.GONE);

					EffectManager.getInstance().ttsPlay(
							EffectManager.TTS_TYPE_TASK, getString(R.string.chooseCancel), false);
				}
				photoAdapter.setCheckable(checkedable);
			}
		});
		
		layout_delete.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				if(photoAdapter.hasCheckItem()){
					dialog(getString(R.string.isDelete));
				} else {
					EffectManager.getInstance().ttsPlay(EffectManager.TTS_TYPE_BASE,
							getString(R.string.choosePicture), false);
				}
			}
		});
		
		layout_camera.setOnClickListener(new OnClickListener(){

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				startCamera();
			}
			
		});

		layout_upload.setOnClickListener(new OnClickListener(){

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				uploadTask = new UploadTask();
				uploadTask.execute();
			}

		});
	}
	
	
	@Override
	protected void onRestart() {
		// TODO Auto-generated method stub
		super.onRestart();
		checkInfo();
		isLoad = false;
	}

	private void checkInfo() {
		View noInfo = (View) findViewById(R.id.tv_noInfo);
		DataManager dm = DataManager.getInstance();
		if (0 == photoAdapter.getItemSize()) {
			noInfo.setVisibility(View.VISIBLE);
		} else {
			noInfo.setVisibility(View.GONE);
		}
	}

	/**
	 * 启动手机拍照界面
	 */
	public void startCamera(){
		
		if (!SDcard.isFileExist(DataBaseManager.PHOTO_FORDER_PATH)) {// 如果目录不存在，则创建目录
			SDcard.creatSDDir(DataBaseManager.PHOTO_FORDER_PATH);
		}
		
		Intent intent = new Intent();
		intent.setAction(MediaStore.ACTION_IMAGE_CAPTURE);
		intent.addCategory("android.intent.category.DEFAULT");
		photo_name = S.getPhotoName("");
		String photoPath = DataBaseManager.PHOTO_FORDER_PATH + photo_name;
		File file = new File(photoPath);  
		Uri uri = Uri.fromFile(file);  
		intent.putExtra(MediaStore.EXTRA_OUTPUT, uri);  
		startActivityForResult(intent, 1);
	}
	
	@Override
	protected void onStart() {
		// TODO Auto-generated method stub
		super.onStart();
		if(gridview_photo.getAdapter()==null)
		{
			gridview_photo.setAdapter(photoAdapter);
		}
		else
		{
			photoAdapter.update();
		}
	}


	private void loadactionbar() {
		// TODO Auto-generated method stub
		actionBar.setCustomView(LayoutInflater.from(PhotoAlbumActivity.this)
				.inflate(R.layout.actionbar_back_and_home, null));
		actionBar.setDisplayOptions(ActionBar.DISPLAY_SHOW_CUSTOM);
		actionBar.setDisplayShowCustomEnabled(true);
		TextView title = (TextView) findViewById(R.id.txt_title);
		title.setText(R.string.PhotoAlbumActivity);
		ImageView back = (ImageView) findViewById(R.id.action_back);
		back.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View arg0) {
				finish();
			}
		});
		ImageView home = (ImageView) findViewById(R.id.action_home);
		home.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				Intent intent = new Intent(PhotoAlbumActivity.this, MainActivity.class);
				intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
				startActivity(intent);
			}
		});
	}
	
	@Override
	public void onActivityResult(int requestCode, int resultCode, Intent data) {
		// TODO Auto-generated method stub
		super.onActivityResult(requestCode, resultCode, data);
		
		if(requestCode == 1&&resultCode!=Activity.RESULT_CANCELED){
			//保存缩略图
			makeImageThumbnails();
			//重新启动相机
			startCamera();
		}
	}
	
	/**
	 * 执行任务
	 */
	private void onDelete() {
		
		//删除选中图片
		photoAdapter.deleteImage();
		checkInfo();
	}
	
	
	/**
	 * 提示dialog
	 */
	private void dialog(String message) {
		AlertDialog.Builder builder = new AlertDialog.Builder(
				PhotoAlbumActivity.this);
		builder.setTitle(getString(R.string.prompt));
		builder.setMessage(message);
		builder.setIcon(android.R.drawable.ic_dialog_info);
		builder.setPositiveButton(getString(R.string.confirm), new DialogInterface.OnClickListener() {
			@Override
			public void onClick(DialogInterface dialog, int which) {
				onDelete();
				dialog.dismiss();
			}
		});
		builder.setNegativeButton(getString(R.string.cancel), new DialogInterface.OnClickListener() {
			@Override
			public void onClick(DialogInterface dialog, int which) {
				dialog.dismiss();
			}
		});
		dialog = builder.create();
		dialog.show();
	}
	
	
	/**
	 * 保存照片缩略图
	 */
	public void makeImageThumbnails()
	{
		BufferedOutputStream bos = null;
		Bitmap bitmap = null;  
		try {
			if(S.isEmpty(photo_name))
			{
				return;
			}
			String photoPath = DataBaseManager.PHOTO_FORDER_PATH + photo_name;
			File file = new File(photoPath);
			//如果没有图片文件，返回
			if(!file.exists())
			{
				return;
			}
			String thumbnails_path = DataBaseManager.DCIM_FORDER_PATH + photo_name;
			//如果目录不存在创建目录
			if (!SDcard.isFileExist(DataBaseManager.DCIM_FORDER_PATH)) 
			{
				SDcard.creatSDDir(DataBaseManager.DCIM_FORDER_PATH);
			}
			//生成缩略图
			if (!SDcard.isFileExist(thumbnails_path))
			{

				SDcard.creatSDFile(thumbnails_path);
			}
	        BitmapFactory.Options options = new BitmapFactory.Options(); 
	        options.inJustDecodeBounds = true; // 设为 false
	        bitmap = BitmapFactory.decodeFile(photoPath, options);  
	        options.inJustDecodeBounds = false; // 设为 false  
	        // 计算缩放比  
	        int h = options.outHeight;  
	        int w = options.outWidth;  
	        int beWidth = w / 90;  
	        int beHeight = h / 90;  
	        int be = 1;  
	        if (beWidth < beHeight) {  
	            be = beWidth;  
	        } else {  
	            be = beHeight;  
	        }  
	        if (be <= 0) {  
	            be = 1;  
	        }  
	        options.inSampleSize = be;  
	        // 重新读入图片，读取缩放后的bitmap，注意这次要把options.inJustDecodeBounds 设为 false  
	        bitmap = BitmapFactory.decodeFile(photoPath, options); 
			bos = new BufferedOutputStream(new FileOutputStream(thumbnails_path));
			//OutputStream os = new FileOutputStream(myCaptureFile);		
			/* 采用压缩转档方法 */						
			bitmap.compress(Bitmap.CompressFormat.JPEG, 100, bos);
			/* 调用flush()方法，更新BufferStream */						
			bos.flush();
						
			/* 结束OutputStream */						
			bos.close();	

		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		 finally{
	        	if(bos!=null)
	        	{
	        		try {
						bos.close();
					} catch (IOException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
	        	}	
	        	if(bitmap!=null&&!bitmap.isRecycled())
	    		{
	    			bitmap.recycle();
					System.gc();
	    		}
	        }

	}

	@Override
	protected void onDestroy() {
		if(uploadTask!=null){
			uploadTask.close();
		}
		System.gc();
		super.onDestroy();
	}

	private class UploadTask extends AsyncTask<Void, Integer, String> {

		private String uploadFileName = "";
		private boolean flag = false;
		private boolean isClose = false;
		@Override
		protected void onCancelled() {
			super.onCancelled();
			//关闭上传图片处理
			UploadTask.this.close();
			//FTP断开连接
			UpdateFile.getInstance().ftpDisconnect();
			//隐藏进度条
			pd.dismiss();
			//上传成功
			if(flag){
				//刷新照片列表
				photoAdapter.notifyDataSetChanged();
			}
		}

		private void close()
		{
			//提示线程开关
			isClose = true;
		}

		@Override
		protected void onPostExecute(String result) {
			super.onPostExecute(result);
		}

		@Override
		protected void onPreExecute() {
			super.onPreExecute();
			if(photoAdapter.hasCheckItem()){
				initProgressDialog();
			}
			else{
				EffectManager.getInstance().ttsPlay(EffectManager.TTS_TYPE_BASE,
						getString(R.string.choosePicture), false);
				this.close();
			}

		}

		@Override
		protected void onProgressUpdate(Integer... values) {
			super.onProgressUpdate(values);
			//如果全部上传成功
			if(pd.getMax()==values[0]){
				onDelete();
				pd.setMessage(getString(R.string.uploadPictureSucceed));
				pd.getButton(DialogInterface.BUTTON1).setText(getString(R.string.confirm));
				flag = true;
				EffectManager.getInstance().ttsPlay(EffectManager.TTS_TYPE_TASK, getString(R.string.uploadPictureSucceed), false);
			}
			else{
				//pd.setMessage("正在上传图片：\n"+uploadFileName);
				pd.setMessage( getString(R.string.uploadingPicture));
			}
			//更新进度条
			pd.setProgress(values[0]);
		}

		@Override
		protected String doInBackground(Void...arg0) {
			if(isClose){
				return null;
			}
			List<File> fileList = photoAdapter.getSelectImage();
			if(fileList==null||fileList.size()==0){
				EffectManager.getInstance().ttsPlay(EffectManager.TTS_TYPE_BASE,
						getString(R.string.choosePicture), false);
				return null;
			}
			pd.setMax(fileList.size());
			int i=0;
			outter:for(File file:fileList){
				i++;
				uploadFileName = file.getName();
				String path = file.getPath();
				//上传文件
				boolean flag = false;
				//如果没有上传成功，重新上传
				while(!flag) {
					if (!isClose) {
						flag = UpdateFile.getInstance().upload(path, uploadFileName);
						WriteLog.getInstance().writeLog(getString(R.string.UP_1) + path + getString(R.string.UP_2) + flag);
						try {
							Thread.sleep(200);
						} catch (InterruptedException e) {
							e.printStackTrace();
						}
					} else {
						break outter;
					}
				}
				publishProgress(i);
			}
			return null;
		}

		/**
		 * 下载APK
		 */
		private void initProgressDialog() {
			// TODO Auto-generated method stub
			pd = new  ProgressDialog(PhotoAlbumActivity.this);
			pd.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
			pd.setTitle(getString(R.string.uploadPicture));
			pd.setMessage(" ");
			pd.setButton(DialogInterface.BUTTON1,getString(R.string.uploadCancel), new DialogInterface.OnClickListener(){
				@Override
				public void onClick(DialogInterface dialog, int which) {
					// TODO Auto-generated method stub
					UploadTask.this.onCancelled();
				}
			});
			pd.show();
		}
	}
}
